package com.zkyc.framework.common.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lbc
 * @since 2022/6/1
 */

@Slf4j
@Service
public class RestTemplateService {

    @Resource
    RestTemplate restTemplate;

    public JSONObject sendRequest(String url,String cookies,HashMap params) {
        List<String> cookieList = new ArrayList<>();
        String[] split = cookies.split(";");
        for (String s : split) {
            cookieList.add(s);
        }
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Host","portal.zhejianglab.com");
        headers.set("Content-Type","application/json");
        headers.set("Cookie",cookies);
        headers.put(HttpHeaders.COOKIE, cookieList);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        JSONObject jsonObject;
        try {
            jsonObject = (JSONObject) restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class,params).getBody();
        } catch (HttpClientErrorException e) {
            return JSONObject.parseObject(e.getResponseBodyAsString());
        }
        if (!StringUtils.isEmpty(jsonObject)) return jsonObject;
        return null;
    }
}

